<template>
    <el-drawer
        append-to-body
        :title="'授权'"
        :modelValue="drawerVisible"
        @update:modelValue="(e)=>{emit('update:drawerVisible',e)}"
        direction="rtl"
    >

        <div class="tree-content">

            <el-tree
                ref="treeRef"
                node-key="id"
                :props="{
                    'label':'displayName'
                }"
                :default-checked-keys="menuIds"
                :data="routeDatas"
                :render-after-expand="true"
                multiple
                show-checkbox
            />

        </div>


        <div class="demo-drawer__footer">
            <el-button @click="emit('update:drawerVisible',false)">Cancel</el-button>
            <el-button @click="sureClick" type="primary">{{
                'Submit'
            }}</el-button>
        </div>
    </el-drawer>
</template>

<script setup>
import { reactive, ref, watch,onUnmounted,onMounted,computed,nextTick } from 'vue'
import {apiRoleMenusGetRoleMenuIds} from "@/api/roleMenus"
import {findParents} from "@/utils/tools"
import {apiRoleMenusUpdate} from "@/api/roleMenus"
import {uniq} from "lodash-es"
import { ElMessage, ElMessageBox } from 'element-plus'
const props = defineProps({
  drawerVisible: {
    type:Boolean,
    default:false
  },
  roleId:{
    type:String,
    default:''
  },
  routeDatas:{
    type:Array,
    default:function() {
      return []
    }
  }
})
const emit = defineEmits(['update:drawerVisible','hanldeRequest']);

const menuIds = ref([]);
const treeRef = ref(null);

async function roleChange(id) {
  const res = await apiRoleMenusGetRoleMenuIds({id})
  menuIds.value = res?.items ?? []
  treeRef.value.setCheckedKeys(menuIds.value)
}

async function sureClick() {
  const res = [];
  const menuIds = treeRef.value.getCheckedKeys(false,false);
  menuIds.forEach((id) => {
    const arr = findParents(props.routeDatas,id);
    res.push(...arr,id);
  });
  console.log('res',res);


  await apiRoleMenusUpdate({
    menuIds:uniq(res),// formParams.value.menuIds, //treeRef.value.getCheckedKeys(false), //
    roleId: props.roleId
  })
  ElMessage({
    type: 'success',
    message: '修改成功',
  })
  emit('update:dialogVisible',false)
}

watch(() => props.roleId,(val) => {
  if(val) {
    nextTick(() => {
      roleChange(val)
    })
  }
},{
  immediate:true
})

</script>

<style lang="scss" scoped>
.demo-drawer__footer {
  position: absolute;
  bottom: 10px;
  right: 10px;
}
</style>